﻿using AutoMapper;
using Mysoft.Common.Extensions;
using Mysoft.Data;
using Mysoft.Domain.Basic;
using Mysoft.Entity;

namespace Mysoft.Domain
{
    public class ErrorLogService : DomainBase
    {
        private readonly EntityService<Sys_ErrorLog> _entityService;

        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="entityService"></param>
        /// <param name="mapper"></param>
        public ErrorLogService(EntityService<Sys_ErrorLog> entityService, IMapper mapper)
        {
            _entityService = entityService;
            _mapper = mapper;
        }


        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="messgae">错误信息</param>
        /// <param name="StackTrace">堆栈错误信息</param>
        /// <returns></returns>
        public async Task<Guid> Write(string messgae,string StackTrace) 
        {
            Sys_ErrorLog log = new Sys_ErrorLog();
            log.CreateGuid = _UserContext.UserInfo.Id;
            log.CreateName = _UserContext.UserInfo.Name;
            log.CreateDate = DateTime.Now;
            log.UpdateGuid = _UserContext.UserInfo.Id;
            log.UpdateName = _UserContext.UserInfo.Name;
            log.UpdateDate = DateTime.Now;
            log.Operator = _UserContext.UserInfo.Name;
            log.OperatorId = _UserContext.UserInfo.Id.Value;
            log.OperatorIP = HttpContext.Current.Connection.RemoteIpAddress?.MapToIPv4().ToString();
            log.Date = DateTime.Now;
            log.Message = messgae;
            log.StackTrace = StackTrace;


            var info = await _entityService.Instance.AddAsync(log);
            return info.Id;
        }

        /// <summary>
        /// 获取全部日志信息
        /// </summary>
        /// <returns></returns>
        public  List<Sys_ErrorLog> GetAll() 
        {
            return _entityService.Instance.Find(m => true);
        }
    }
}
